package com.huawang.mdesign.model.service.util;

import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public final class CommonUtil {

    private CommonUtil() {
    }

    @Autowired
    private static Map<String, Object> charWidthConfig;

    @NotNull
    public static Integer getTextWidth(String str, Integer fontSize) {
        return getTextWidth(str, fontSize, "");
    }

    @NotNull
    public static Integer getTextWidth(String str, Integer fontSize, String fontFamily) {
        if (fontFamily == null) {
            fontFamily = "";
        }
        if (Objects.isNull(str)) {
            return 0;
        }
        int width = 0;
        final Integer scale = fontSize / 12;
        Integer charWidth;
        final int oneFontSize = fontSize * 1000;
        final int length = str.length();
        HashMap<String, Integer> fontFamilyConfig = Objects.nonNull(charWidthConfig) ?
                (HashMap<String, Integer>) charWidthConfig.get(fontFamily) : null;
        for (int i = 0; i < length; i++) {
            String ch = str.charAt(i) + "";
            charWidth = Objects.nonNull(fontFamilyConfig) ? fontFamilyConfig.get(ch) : null;
            if (Objects.nonNull(charWidth)) {
                charWidth = charWidth * scale;
            } else {
                charWidth = oneFontSize;
            }
            width += charWidth;
        }
        return (int) (Math.ceil(width / 1000d) + 2);
    }

    @NotNull
    public static List<Integer> getWrapTextWidths(String str, Integer fontSize, Integer limitWidth) {
        String fontFamily = "";
        limitWidth -= 2;
        limitWidth *= 1000;
        int width = 0;
        String ch;
        Integer charWidth;
        final List<Integer> widths = new ArrayList<>();
        if (Objects.isNull(str)) {
            return widths;
        }
        final Integer scale = fontSize / 12;
        final int oneFontSize = fontSize * 1000;
        HashMap<String, Integer> fontFamilyConfig = Objects.nonNull(charWidthConfig) ?
                (HashMap<String, Integer>) charWidthConfig.get(fontFamily) : null;
        for (int i = 0; i < str.length(); i++) {
            ch = str.charAt(i) + "";
            charWidth = Objects.nonNull(fontFamilyConfig) ? fontFamilyConfig.get(ch) : null;
            if(Objects.nonNull(charWidth)){
                charWidth = charWidth * scale;
            }else{
                charWidth = oneFontSize;
            }

            if(width + charWidth > limitWidth){
                widths.add(width / 1000 + 2);
                width = charWidth;
            }else{
                width += charWidth;
            }
        }
        widths.add(width / 1000 + 2);
        return widths;
    }
}
